package ZCrIS::validate_zip_code;

sub run {
  my ($class, $zR) = @_;

  my $package = __PACKAGE__;
  $package =~ s/.*://;
  my $plugin = 'Plugin ' . $package;

  $zR->log->DEBUG($plugin . ' located.') if $zR->debugging;

  unless (
    $zR->payload->{form} &&
    $zR->payload->{zip}
  ) {
    $zR->fail('invalidPayload');
  }

  $zR->addWebClient;

  $zR->log->DEBUG($plugin . ' issuing web request...')
     if $zR->debugging;
  my $response = $zR->webClient->get(
    'http://www.webservicex.net/uszip.asmx/GetInfoByZIP?USZip=' .
      $zR->payload->{zip}
  );

  my $isFailure = undef;
  my $body = undef;

  if ($response->is_success) {
    $zR->log->DEBUG($plugin . ' received web response.')
      if $zR->debugging;
    my $data = $zR->xmlParser->XMLin($response->content);
    my $table = $data->{Table};
    if ($table) {
      $zR->log->DEBUG($plugin . ' found zip code.') if $zR->debugging;
      $body = <<EOF;
City : $table->{CITY} 
State : $table->{STATE}
Zip : $table->{ZIP}
ZCrIS Operation : request
ZCrIS Success : true
ZCrIS Message : zip code found.
ZCrIS Garbage Can : true
EOF
    }
    else {
      $zR->log->DEBUG($plugin . ': zip code not found.') if $zR->debugging;
      my $incomingZip = $zR->payload->{zip};
      $body = <<EOF;
City : unknown 
State : unknown
Zip : $incomingZip
ZCrIS Operation : request
ZCrIS Success : false
ZCrIS Message : zip code not found.
ZCrIS Garbage Can : false
EOF
    }
  }
  else {
    $isFailure= 1;
    $zR->log->DEBUG($plugin . ': Invalid response from service.') if $zR->debugging;
    my $incomingZip = $zR->payload->{zip};
    $body = <<EOF;
City : unknown
State : unknown
Zip : $incomingZip
ZCrIS Operation : request
ZCrIS Success : false
ZCrIS Message : sorry, service is experiencing difficulties so we could not validate this zip code.
ZCrIS Garbage Can : false
EOF
  }
  $zR->payload->{form} .= '@forms.zohocreator.com'
    unless $zR->payload->{form} =~ /\@.+$/;
  my %outgoingHeaders = (
    Subject => 'Zip Code Validation Report',
    To      => $zR->payload->{form},
    Cc      => $zR->incomingMessage->from,
  );
  $zR->log->DEBUG($plugin . ' sending response message...') if $zR->debugging;
  $zR->sendOutgoingMessage(\%outgoingHeaders, $body);
  $zR->fail('serviceUnavailable') if $isFailure;
}

1;
